/*
 * Copyright 1999-2012 Alibaba.com All right reserved. This software is the
 * confidential and proprietary information of Alibaba.com ("Confidential
 * Information"). You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license agreement you entered
 * into with Alibaba.com.
 */
package cn.com.topchoice.mobile.library.util;

import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;

/**
 * The File Help Util
 * 
 * @author dengjiebin
 * @date 2012-4-5
 */
public final class FileUtil {

	private static final char HEX_DIGITS[] = { '0', '1', '2', '3', 
		'4', '5', '6', '7', '8', '9',
		'A', 'B', 'C', 'D', 'E', 'F' };
	
	/**
	 * calculate a message-digest fingerprint for the specified file
	 * 
	 * @param filePath
	 * @return
	 */
	public static String md5sum(String filePath) {
		InputStream fis;
        byte[] buffer = new byte[1024];
        int numRead = 0;
        MessageDigest md5;
        try{
            fis = new FileInputStream(filePath);
            md5 = MessageDigest.getInstance("MD5");
            while ((numRead = fis.read(buffer)) > 0) {
                md5.update(buffer,0,numRead);
            }
            fis.close();
            return toHexString(md5.digest());
        } catch (Exception e) {
            return null;
        }
	}
	
	/**
	 * Convert the byte array to the hex string
	 * 
	 * @param data
	 * @return
	 */
	public static String toHexString(byte[] data) {
		StringBuilder sb = new StringBuilder(data.length * 2);
		for (int i = 0; i < data.length; i++) {
			sb.append(HEX_DIGITS[(data[i] & 0xf0) >>> 4]);
			sb.append(HEX_DIGITS[data[i] & 0x0f]);
		}
		return sb.toString();
	}

}